<template>
  <slot v-if="loaded"></slot>
  <div v-else ref="box" :style="{ height, width }">
    <slot name="loading"></slot>
  </div>
</template>
<script setup lang="ts">
import { initLazyIntersectionObserver } from '@/utils'

defineProps({
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  }
})

const loaded = ref(false)

const box = ref<null | Element>(null)

let observer

onMounted(() => {
  observer = initLazyIntersectionObserver((entry) => {
    if (entry.isIntersecting) {
      // 当内容可见
      loaded.value = true
      // @ts-ignore
      observer.unobserve(box.value)
      observer = null
    }
  })
  // @ts-ignore
  box.value && observer.observe(box.value) // 观察
})

// @ts-ignore
onBeforeUnmount(() => observer && observer.unobserve(box.value.$el)) // 不观察了
</script>
